package com.yantong.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yantong.pojo.*;
import com.yantong.constant.PermisFlag;
import com.yantong.result.ApiResult;
import com.yantong.service.CentreService;
import com.yantong.utils.ShiroUtils;
import com.yantong.service.UserService;
import com.yantong.service.MemberService;
import com.yantong.utils.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kanghaixin
 */
@Controller
public class BaseController {

    public static final int WXPAY_ORDER = 0; //订单支付
    public static final int WXPAY_VIP = 1;   //购买vip
    public static final int WXPAY_SHIPCARD = 2;   //购买充值卡
    public static final int WXPAY_LOCALLIFE_VIP = 3;   //本地生活会员
    public static final int WXPAY_LOCALLIFE_PREFERENTIAL_CARD = 4; //本地生活商户优惠卡
    private static final double VIP_PRICE = 199;


    @Autowired
    private UserService userService;
    @Autowired
    private CentreService centreService;
    @Autowired
    private MemberService memberService;


    public SysUser getUser() {
        return ShiroUtils.getUser();
    }

    public Long getUserId() {
        return getUser().getUserId();
    }

    public String getUsername() {
        return getUser().getName();
    }

    public String getNikeName() {
        return getUser().getNickname();
    }

    public String getUserFlag() {
        return getUser().getFlag();
    }

    public Long getUserTeamId() {
        return getUser().getTeamId();
    }

    public Long getUserCentreId() {
        SysUserCentre userCentre = userService.getUserCentre(getUserId());
        if (userCentre == null || userCentre.getCentreId() == null) {
            return null;
        }
        return userCentre.getCentreId();
    }

    public String getCentreName() {
        SysUserCentre userCentre = userService.getUserCentre(getUserId());
        if (userCentre == null || userCentre.getCentreId() == null) {
            return null;
        }
        return centreService.getByKey(userCentre.getCentreId()).getName();
    }



    /**
     * 根据账号类型获取页面上centreId相关数据
     *
     * @return
     */
    public Map<String, Object> getCentreIdModelInfo() {
        Map<String, Object> map = new HashMap<>(4);
        if (PermisFlag.FLAG_CENTRE.equals(getUserFlag()) || PermisFlag.FLAG_SHOP.equals(getUserFlag())) {
            map.put("centreId", getUserCentreId());
            map.put("flag", PermisFlag.FLAG_CENTRE);
            Long teamId = getUserTeamId();
            if (null != teamId) {
                map.put("teamId", teamId);
                map.put("teamInfo", memberService.getByKey(teamId));
            }else{
                Map mapParam = new HashMap<>();
                mapParam.put("centreId", getUserCentreId());
                mapParam.put("isteam", 3);
                List<Member> entityList = memberService.getAllMember(mapParam);
                map.put("teamList", entityList);
                map.put("showTeam", 1);
            }
            List<Centre> centreList = new ArrayList<>();
            Centre centre = centreService.getByKey(getUserCentreId());
            centreList.add(centre);
            map.put("centreList", centreList);
        } else if (PermisFlag.FLAG_PLATFORM.equals(getUserFlag())) {
            map.put("flag", PermisFlag.FLAG_PLATFORM);
            map.put("centreList", centreService.listAllCentres());
        }
        return map;
    }

    public Long getMemberId(String authToken) {
        String tokenString = null;
        try {
            tokenString = new String(Base64Utils.decodeFromString(authToken), StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        JSONObject authTokenJson = JSON.parseObject(tokenString);
        return authTokenJson.getLong("id");
    }

    /**
     * 根据账号类型获取页面上teamId相关数据
     *
     * @return
     */
    public Map<String, Object> getTeamIdModelInfo() {
        Map map = new HashMap<>();
        map.put("centreId", getUserCentreId());
        map.put("isteam", 3);
        List<Member> entityList = memberService.getAllMember(map);
        Map<String, Object> result = new HashMap();
        result.put("teamList", entityList);
        Long teamId = getUserTeamId();
        if ( teamId == null) {
            result.put("teamFlag", "0");
        } else {
            result.put("teamFlag", "1");
            map.put("teamId", teamId);
        }
        return result;
    }

    /**
     * 根据商户ID获取页面上teamId相关数据
     *
     * @return
     */
    public Map<String, Object> getTeamIdList(Long centreId) {
        Map map = new HashMap<>();
        map.put("centreId", centreId);
        map.put("isteam", 3);
        List<Member> entityList = memberService.getAllMember(map);
        Map<String, Object> result = new HashMap();
        result.put("teamList", entityList);
        if (getUserTeamId() == null) {
            result.put("teamFlag", "0");
        } else {
            result.put("teamFlag", "1");
        }
        return result;
    }

    /**
     * @param requestCode
     * @param msg
     * @param data
     * @return Map<String, Object>
     * @throws
     * @Description:构建统一格式返回对象
     * @date 2016年9月2日
     * @author zhuliyun
     */
    public ApiResult toResponsObject(String requestCode, String msg, Object data) {
        ApiResult obj = new ApiResult(requestCode, msg);
        if (data != null)
            obj.setData(data);

        return obj;
    }

    public ApiResult toResponsSuccess(Object data) {
        ApiResult rp = toResponsObject("0", "操作成功", data);
//        logger.info("response:" + rp);
        return rp;
    }

    public ApiResult toResponsMsgSuccess(String msg) {
        return toResponsObject("0", msg, "");
    }

    public ApiResult toResponsFail(String msg) {
        return toResponsObject("500", msg, null);
    }

    public String getTheme(){
        String theme = "default";
        return theme;
    }

    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}